package com.dingpeikeji.quickdeer.modules.base.web;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;

import com.dingpeikeji.quickdeer.core.modules.sys.entity.User;
import com.dingpeikeji.quickdeer.modules.base.service.FrontUserService;

/**
 * 自动登录的过滤器的实现
 * 
 * @author admin
 *
 */
public class AutoLoginFilter implements Filter {
	public static final String FRONT_USER_IN_SESSION = "front_user";
	public static final String SAVE_USER_FOR_TREE_MONTHS = "saveUserFor3Months";
	@Autowired
	private FrontUserService frontUserService;
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		/**
		 * 判断session中是否有用户的信息: * session中如果有:放行. * session中没有: * 从Cookie中获取: *
		 * Cookie中没有:放行. * Cookie中有: * 获取Cookie中存的用户名和密码到数据库查询. * 没有查询到:放行. *
		 * 查询到:将用户信息存入到session . 放行.
		 */
		// 判断session中是否有用户的信息:
		HttpServletRequest req = (HttpServletRequest) request;
		HttpSession session = req.getSession();
		User existUser = (User) session.getAttribute(FRONT_USER_IN_SESSION);
		WebApplicationContext context = 
				(WebApplicationContext) session.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
		FrontUserService frontUserService = (FrontUserService) context.getBean("frontUserService");
		if (existUser != null) {
			// session中有用户信息.
			chain.doFilter(req, response);
		} else {
			// session中没有用户信息.
			// 获得Cookie的数据:
			Cookie[] cookies = req.getCookies();
			Cookie cookie = CookieUtils.findCookie(cookies, "autoLogin");
			// 判断Cookie中有没有信息:
			if (cookie == null) {
				// 没有携带Cookie的信息过来:
				chain.doFilter(req, response);
			} else {
				// 带着Cookie信息过来.
				String value = cookie.getValue();// aaa#111
				// 获得用户名和密码:
				String username = value.split("#")[0];
				String password = value.split("#")[1];
				// 去数据库进行查询:
				existUser = frontUserService.findUser(username,password);
				try {
					if (existUser == null) {
						// 用户名或密码错误:Cookie被篡改的.
						chain.doFilter(req, response);
					} else {
						// 将用户存到session中,放行
						session.setAttribute(FRONT_USER_IN_SESSION, existUser);
						chain.doFilter(req, response);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public void destroy() {
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

}
